package com.wwg.util.valid;

import com.wwg.common.FinanceException;
import org.hibernate.validator.HibernateValidator;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * 
 *类描述: java 对象属性校验工具类
 *
 *@Author:李志雄
 *@date:2020年6月5日
 *@Version:1.0
 */
public class WsnValidationUtil {
    /**
     * 开启快速结束模式 failFast (true)
     */
    private static Validator validator = Validation.byProvider(HibernateValidator.class).configure().failFast(true).buildValidatorFactory().getValidator();
    
    /**
     * 校验对象
     *
     * @param t bean 校验的对象
     * @param groups 校验组
     * @return ValidResult
     */
    public static <T> ValidResult validateBean(T t,Class<?>...groups) {
        ValidResult result = new WsnValidationUtil().new ValidResult();
        Set<ConstraintViolation<T>> violationSet = validator.validate(t,groups);
        boolean hasError = violationSet != null && violationSet.size() > 0;
        result.setHasErrors(hasError);
        if (hasError) {
            for (ConstraintViolation<T> violation : violationSet) {
                result.addError(violation.getPropertyPath().toString(), violation.getMessage());
            }
        }
        return result;
    }
    
    
    /**
     * 校验对象
     *
     * @param t bean 校验的对象
     * @return ValidResult
     */
    public static <T> ValidResult validateBean(T t) {
        ValidResult result = new WsnValidationUtil().new ValidResult();
        Set<ConstraintViolation<T>> violationSet = validator.validate(t);
        boolean hasError = violationSet != null && violationSet.size() > 0;
        result.setHasErrors(hasError);
        if (hasError) {
            for (ConstraintViolation<T> violation : violationSet) {
                result.addError(violation.getPropertyPath().toString(), violation.getMessage());
            }
        }
        return result;
    }
    
    /**
     * 校验bean的某一个属性
     *
     * @param obj          bean
     * @param propertyName 属性名称
     * @return ValidResult
     */
    public static <T> ValidResult validateProperty(T obj, String propertyName) {
        ValidResult result = new WsnValidationUtil().new ValidResult();
        Set<ConstraintViolation<T>> violationSet = validator.validateProperty(obj, propertyName);
        boolean hasError = violationSet != null && violationSet.size() > 0;
        result.setHasErrors(hasError);
        if (hasError) {
            for (ConstraintViolation<T> violation : violationSet) {
                result.addError(propertyName, violation.getMessage());
            }
        }
        return result;
    }
    /**
     * 校验结果类
     */
    public class ValidResult {
    	//返回错误信息格式： 只显示错误消息
    	public final static int FORMAT_MSG = 0;
    	//返回错误信息格式： 错误字段 + 错误消息
    	public final static int FORMAT_FEILD_MSG = 1;

        /**
         * 是否有错误
         */
        private boolean hasErrors;

        /**
         * 错误信息
         */
        private List<ErrorMessage> errors;

        public ValidResult() {
            this.errors = new ArrayList<>();
        }
        public boolean hasErrors() {
            return hasErrors;
        }

        public void setHasErrors(boolean hasErrors) {
            this.hasErrors = hasErrors;
        }

        /**
         * 获取所有验证信息
         * @return 集合形式
         */
        public List<ErrorMessage> getAllErrors() {
            return errors;
        }
        
        /**
         * 获取所有验证信息
         * @return  
         * @功能描述:
         * @Author:李志雄
         * @date:2020年7月8日  下午6:38:54
         * @Version:1.0
         */
        public String getErrors(){
            StringBuilder sb = new StringBuilder();
            for (ErrorMessage error : errors) {
            	// 字段名：消息;
            	sb.append(error.getPropertyPath()).append(":").append(error.getMessage()).append("; ");
            }
            return sb.toString();
        }
        
        /**
         * 获取所有验证信息
         * @param errorFormat 错误消息返回格式
         * @return  
         * @功能描述:
         * @Author:李志雄
         * @date:2020年7月8日  下午6:38:54
         * @Version:1.0
         */
        public String getErrors(int errorFormat){
            StringBuilder sb = new StringBuilder();
            for (ErrorMessage error : errors) {
            	// 字段名：消息;
            	if(FORMAT_FEILD_MSG == errorFormat)
            	{
            		sb.append(error.getPropertyPath()).append(":").append(error.getMessage()).append("; ");
            	}
            	// 消息;
            	else if(FORMAT_MSG == errorFormat)
            	{
            		sb.append(error.getMessage()).append("; ");
            	}
            	// 消息;
            	else 
            	{
            		sb.append(error.getMessage()).append("; ");
				}
            }
            return sb.toString();
        }

        /**
         * 获取任意一个所有验证信息
         * @param errorFormat 错误消息返回格式
         * @return  
         * @功能描述:
         * @Author:李志雄
         * @date:2020年7月8日  下午6:35:17
         * @Version:1.0
         */
        public String getError(int errorFormat){
            for (ErrorMessage error : errors) {
            	//// 字段名：消息
            	if(FORMAT_FEILD_MSG == errorFormat)
            	{
            		return error.getPropertyPath() + ": " + error.getMessage();
            	}
            	// 消息
            	else if(FORMAT_MSG == errorFormat)
            	{
            		return error.getMessage();
            	}
            	// 消息
            	else {
            		return error.getMessage();
				}
            }
            return null;
        }
        
        public void addError(String propertyName, String message) {
            this.errors.add(new ErrorMessage(propertyName, message));
        }
    }

    public class ErrorMessage {

        private String propertyPath;

        private String message;

        public ErrorMessage() {
        }

        public ErrorMessage(String propertyPath, String message) {
            this.propertyPath = propertyPath;
            this.message = message;
        }

		public String getPropertyPath() {
		
			return propertyPath;
		}

		public String getMessage() {
		
			return message;
		}
        
    }

    public static void main(String[] args) {
        /**
         * 银行推送感知提货单影像文件
         */
//        public ResponseModel handleDeliveryOrderFile(CzbDeliveryOrderFileModel deliveryOrderFileModel) throws FinanceException {
//            ResponseModel responseModel = new ResponseModel(true, CzbResultDic.RESULT_CODE_SUCCESS,CzbResultDic.RESULT_MSG_SUCCESS);
//
//            // 参数校验
//            WsnValidationUtil.ValidResult validResult = WsnValidationUtil.validateBean(deliveryOrderFileModel);
//            if (validResult.hasErrors()) {
//                responseModel.setResultCode(CzbResultDic.FAIL_CODE);
//                responseModel.setResultMsg(validResult.getError(WsnValidationUtil.ValidResult.FORMAT_MSG));
//                responseModel.setSuccess(false);
//                return responseModel;
//            }
    }

}
